home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3402 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: quasar.engr.sgi.com!davea
  2. From: davea@quasar.engr.sgi.com (David B.Anderson)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Checking to See if a File Exists
  5. Date: 28 Jan 1996 18:47:50 GMT
  6. Organization: Silicon Graphics, Inc., Mountain View, CA
  7. Message-ID: <4eggcm$o0j@fido.asd.sgi.com>
  8. References: <DLtI7G.HpE@midway.uchicago.edu> <9601281412.AA0001c@doodey.demon.co.uk>
  9. NNTP-Posting-Host: quasar.engr.sgi.com
  10.  
  11. In article <9601281412.AA0001c@doodey.demon.co.uk>,
  12. Paul F. Robinson <pfr@doodey.demon.co.uk> wrote:
  13. >josef jurek (jaj3@kimbark.uchicago.edu) wrote:
  14. >: 
  15. >: How does one check from a C program to see whether a file
  16. >: exists or not?
  17. >Your compiler library might have an  access()  function.
  18.  
  19. Be careful: on  UN*X systems, access() uses different file
  20. permissions checks than open()(or fopen()) to deterimine if 
  21. you are allowed to get at the file.
  22.  
  23. And indeed neither open() nor fopen() nor access() prove the
  24. file does not exist when they fail. All it proves is that you
  25. cannot open(), fopen() or access() the file.
  26.  
  27. Of course on machines and/or file systems without any notion of
  28. file permissions any of them you have available may do what you want.
  29.  
  30. >Alternatively,
  31. >attempt to open the file with fopen().
  32. >If successful, the file exists. -Don't forget to fclose() it.
  33. >If unsuccessful, check the value of errno. ENOENT (from errno.h)
  34. > indicates that the file does not exist.
  35.  
  36. fopen() is not guaranteed by ISO C to set errno at all.  If you
  37. are dealing with XPG4-compliant systems, you do get a
  38. stronger guarantee: xpg4 does guarantee errno is set.  Cautious
  39. folks will set errno to 0 before calling fopen() so if it
  40. *fails* to set errno you can tell it failed to do so.
  41.  
  42. I don't have the POSIX doc here at home, but do have XPG4 doc
  43. available, so I checked that... and ISO C.
  44.  
  45. A better choice than fopen()/open()/access() would be one of
  46. the 'stat' functions, such as stat() (or lstat()).   Because
  47. they will not fail due to lack of permission on the file.  If
  48. you have them available.
  49.  
  50. What you use will depend on what you are going to do with the
  51. information that the file exists.  You should consider putting
  52. the code into a separate function and documenting the function
  53. as being a potential portability problem.
  54.  
  55. Regards,
  56. [ David B. Anderson              (415)933-4263            davea@sgi.com      ]
  57. [ Suddenly to me that no verb in this sentence.                        -m.toy]
  58.